package cn.bdqn.bean;

import cn.bdqn.domain.Doctor;
import cn.bdqn.domain.Nurse;
import cn.bdqn.mapper.DoctorMapper;
import cn.bdqn.mapper.NurseMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;


public class MyRealm extends AuthorizingRealm {

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private NurseMapper nurseMapper;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        System.out.println("--------------------------------------");
        //先把数据查出来
        Doctor doctor = doctorMapper.selectByDoctorNumber(principal);
        Nurse nurse = nurseMapper.selectByCard(principal);

        if (doctor != null){

            if (!ObjectUtils.isEmpty(doctor)){
                return new SimpleAuthenticationInfo(doctor.getDoctorNumber(),doctor.getDoctorPassword(),
                        ByteSource.Util.bytes(doctor.getSalt()),this.getName());
            }
        }

        if (nurse != null){

            if (!ObjectUtils.isEmpty(nurse)){
                return new SimpleAuthenticationInfo(nurse.getCard(),nurse.getPassword(),
                        ByteSource.Util.bytes(nurse.getSalt()),this.getName());
            }
        }


        return null;
    }
}
